/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.members;

import com.alibaba.fastjson.JSONObject;
import com.qinyeit.serviceapp.entity.DeliveryDetail;
import com.qinyeit.serviceapp.entity.MemberCardType;
import com.qinyeit.serviceapp.entity.enums.DeliveryState;
import com.qinyeit.serviceapp.entity.enums.PeriodType;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.service.branchs.BranchDataReleasedServiceImpl;
import com.qinyeit.serviceapp.service.members.DeliveryDetailService;
import com.qinyeit.serviceapp.service.members.MemberCardService;
import com.qinyeit.serviceapp.service.members.MemberCardTypeService;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;

import com.qinyeit.serviceapp.entity.DeliveryRecord;
import com.qinyeit.serviceapp.service.members.DeliveryRecordService;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.transaction.Transactional;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * ClassName: DeliveryRecordsController <br/>
 * Function: deliveryRecord [配送记录] <br/>
 * date: 2018-12-04 11:14:55 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/members/deliveryRecords")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_deliveryRecord:read",name ="配送记录",deleteAble = false)
public class DeliveryRecordsController extends BaseManagementController{

	@Autowired
	private DeliveryRecordService deliveryRecordService;
	@Autowired
    private MemberCardTypeService memberCardTypeService;
	@Autowired
    private BranchDataReleasedServiceImpl branchDataReleasedService;

	private final String [] keys = {"id","batch.id:batchId","cardTypeId","branchId","branchName","startNo","endNo","count","createAt"};

    @RequiresPermissions("management_deliveryRecord:show")
    @PermissionInfo(code = "management_deliveryRecord:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable){
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        Page<DeliveryRecord> deliveryRecordPage = deliveryRecordService.findAll(searchable);
        QyMap map = QyMap.map("deliveryRecordPage",JSONUtils.include(deliveryRecordPage, keys));
        //会员卡类型
        searchable = SearchableUtils.newSearchableWithMerchantFilter();
        List<MemberCardType> typeList = memberCardTypeService.findWithSort(searchable);
        map.setv("typeList",JSONUtils.include(typeList,"id","name"));
        return ok("查询成功", map);
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(){
        QyMap map=QyMap.NEW();
        map.setv("deliveryRecord",JSONUtils.include(new DeliveryRecord(), keys));
        initFormDate(map);
        return ok("初始化成功", map);
    }

    /**
     * 配送
     * @param deliveryRecord
     * @param bindingResult
     * @return
     */
    @RequiresPermissions("management_deliveryRecord:create")
    @PermissionInfo(code = "management_deliveryRecord:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@ModelAttribute @Valid DeliveryRecord deliveryRecord, BindingResult bindingResult){
//        if(deliveryRecordService.exists(buildExists(null, "no", deliveryRecord.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        if (deliveryRecord.getCount()<=0){
            throw new BusinessRunTimeException("配送数量不能小于1",1001);
        }
        if(StringUtils.isBlank(deliveryRecord.getStartNo()) || StringUtils.isBlank(deliveryRecord.getEndNo())){
            throw new BusinessRunTimeException("起始编号或结束编号不能为空",1002);
        }
        deliveryRecord.setMerchantGroupId(CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        deliveryRecord = deliveryRecordService.save(deliveryRecord);
        //配送明细
        deliveryRecordService.saveDetail(deliveryRecord);
        //保存会员卡到对应门店
        branchDataReleasedService.deliveryMemberCard(deliveryRecord);
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute DeliveryRecord deliveryRecord){
        return ok("查询成功", JSONUtils.include(deliveryRecord, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute DeliveryRecord deliveryRecord){
        QyMap map=QyMap.NEW();
        map.setv("deliveryRecord",JSONUtils.include(deliveryRecord, keys));
        initFormDate(map);
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_deliveryRecord:update")
    @PermissionInfo(code = "management_deliveryRecord:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@ModelAttribute @Valid DeliveryRecord deliveryRecord,BindingResult bindingResult){
//        if(deliveryRecordService.exists(buildExists(null, "no", deliveryRecord.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        deliveryRecordService.update(deliveryRecord);
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_deliveryRecord:destory")
    @PermissionInfo(code = "management_deliveryRecord:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        //1.根据配送明细和会员卡（卡号）左关联后 count 条件vip_id is not NULL and 配送ID
        Long count =  deliveryRecordService.getBindVips(id);
        if(count.intValue()>0){
            return fail("配送的此批卡中已经有使用的卡号，不允许删除！");
        }
        //删除门店的对应会员卡
        branchDataReleasedService.deletedMemberCard(id);
        //删除配送记录
        deliveryRecordService.deleteData(id);
        return ok("删除成功", null);
    }


    /**
     * 查看会员卡明细
     * @param id
     * @return
     */
    @GetMapping("/showDetails")
    public ResponseResult<String> showDetails(Long id,Searchable searchable){
        Page<Map<String,Object>>  mapPage = deliveryRecordService.showDetails(id,searchable);
        return ok("查询成功",mapPage);
    }

    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            DeliveryRecord deliveryRecord = deliveryRecordService.findById(Long.valueOf(id));
            model.addAttribute(deliveryRecord);
        }
    }


    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){
    }

}